/**
 * 面试列表页
 */
import React from 'react';
import { router, withRouter } from 'umi';
import { Button, Form } from 'antd';
import { isEqual } from 'lodash';
import { useRequest } from '@/hooks';
import { Pagination } from '@/components';
import AuthComponent from '@/utils/auth/AuthComponent';

import { CustomSearch } from '../components';
import styles from './List.less';
import { HireCommonTable } from '../containers';

import { getHireList } from '../service';

function HireList({ form, recruitCode, location, onDataExchange, isPrincipal, isLauncher }) {
    const { query } = location;
    const { queryStr, employStatus, talentSex } = query;

    // 需转换成数字
    let { pageNo = 1, pageSize = 10 } = query;
    const toNumber = val => (val ? Number(val) : undefined);
    pageNo = toNumber(pageNo);
    pageSize = toNumber(pageSize);

    const condition = React.useMemo(
        () => ({
            pageNo,
            pageSize,
            employStatus,
            talentSex,
            query: queryStr,
            recruitCode: recruitCode ?? 'R11316223198085255169'
        }),
        [JSON.stringify(query, recruitCode)]
    );

    // 设置条件
    const setCondition = n => {
        history.push({ query: { ...query, ...n } });
    };

    // 查询
    const { data, loading, run } = useRequest(() => getHireList(condition), {
        refreshDeps: [JSON.stringify(condition)]
    });

    /**
     * 获取表单数据
     */
    const getFormCondition = React.useCallback(async () => {
        let values = {};
        try {
            values = await form.validateFields();
        } catch (error) {
            console.log(error);
        }
        return values;
    }, []);
    // 刷新
    const handleRefresh = React.useCallback(() => {
        run();
        onDataExchange();
    }, [run]);

    // 表格变化
    const handleTableChange = async (pagination, filters) => {
        const values = await getFormCondition();
        const con = Object.keys(filters).reduce(
            (ret, key) => {
                const item = filters[key];
                return { ...ret, [key]: item.length > 0 ? item[0] : '' }; // 单选?
            },
            { pageNo: 1 }
        );
        setCondition({ ...con, ...values });
    };

    // 跳转明细
    const handleJumpDetail = React.useCallback(async ({ recruitTalentMatcherId, employId, candidateId }) => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/resume/detail',
            query: { id: recruitTalentMatcherId, employId, candidateId, activeKey: 'HIRE' }
        });
    }, []);
    // 点击查询
    const handleSearch = async val => {
        const values = await getFormCondition();
        const newPart = { ...values, ...val, pageNo: 1 };
        if (isEqual(query, { ...query, ...newPart })) {
            run();
        } else {
            setCondition(newPart);
        }
    };
    // 表格
    const renderTable = () => (
        <HireCommonTable
            isPrincipal={isPrincipal}
            isLauncher={isLauncher}
            onJumpDetail={handleJumpDetail}
            condition={condition}
            loading={loading}
            onRefresh={handleRefresh}
            dataSource={data?.data?.rows || []}
            onChange={handleTableChange}
        ></HireCommonTable>
    );

    return (
        <>
            <AuthComponent code="office:recruitment:course:hire:search">
                <Form layout="inline">
                    <header className={styles.headerWrapper}>
                        <div className={styles.conditionWrapper}>
                            <Form.Item>
                                {form.getFieldDecorator('queryStr', { initialValue: queryStr })(
                                    <CustomSearch
                                        onSearch={val => {
                                            if (!val && !query.queryStr) return;
                                            handleSearch({ queryStr: val });
                                        }}
                                        placeholder="搜索姓名、手机"
                                    />
                                )}
                            </Form.Item>
                            <Button type="primary" style={{ marginLeft: 12 }} onClick={() => handleSearch()}>
                                搜索
                            </Button>
                        </div>
                    </header>
                </Form>
            </AuthComponent>
            {renderTable()}
            <Pagination
                current={pageNo}
                pageSize={pageSize}
                total={data?.data?.total}
                loading={loading}
                onChange={value => {
                    const { current, ...rest } = value;
                    setCondition({ ...rest, pageNo: current });
                }}
            />
        </>
    );
}

export default Form.create()(withRouter(HireList));
